<?php
declare(strict_types=1);

namespace app\admin\controller;

use app\common\model\SysMerchant;
use app\common\model\SysMerchantWithdraw;
use app\common\model\SysMerchantWithdrawBill;
use app\common\model\SysMerchantWithdrawLog;
use app\common\model\SysPicInfo;
use think\admin\Controller;
use think\admin\extend\CodeExtend;
use think\facade\Db;

/**
 * 商家管理
 */
class Merchant extends Controller{

    /**
     * 商家列表
     * @auth true
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function index(){
        $this->title = '商家列表';
        $query = SysMerchant::mQuery();
        $user = $this->app->session->get('user');
        if($user['id'] != 10000) $query->where('merchant_id', '=', $user['id']);
        $query->like('shop_name');
        $query->order('gmt_created desc')->page();
    }

    public function _index_page_filter(array &$data){
        foreach ($data as &$vo){
            $cwLst = SysMerchantWithdraw::where(['merchant_id' => $vo['merchant_id']])->find();
            $vo['income_amount'] = isset($cwLst) ? $cwLst['income_amount'] : 0.00;
            $vo['withdrawn_amount'] = isset($cwLst) ? $cwLst['withdrawn_amount'] : 0.00;
            $vo['withdrawal_amount'] = isset($cwLst) ? $cwLst['withdrawal_amount'] : 0.00;
        }

    }

    /**
     * 提现审核
     * @auth true
     * @return void
     */
    public function apply()
    {
        $data = $this->_vali([
            'merchant_id.require' => 'ID不能为空！',
        ]);
        $this->show = $show = SysMerchant::where('merchant_id', '=', $data['merchant_id'])->find();
        $mWithdraw = SysMerchantWithdraw::where(['merchant_id' => $data['merchant_id']])->find();
        if ($this->request->isGet()) {
            $this->show->withdrawal_amount = $mWithdraw['withdrawal_amount'];
            $this->fetch('apply');
        }else{
            $params = $this->_vali([
                'merchant_id.require' => 'ID不能为空！',
                'withdrawal_amount.require' => '提现金额不能为空',
                'pic.require' => '转账凭证不能为空',
                'remark.default' => ''
            ]);
            $amount = $params['withdrawal_amount'];
            if($amount <= 0){
                $this->error('提现金额异常');
            }
            if($amount > $mWithdraw['withdrawal_amount']) $this->error('提现金额超出范围');

            Db::startTrans();
            try {
                //提现表处理
                $withdrawn_amount = bcadd($mWithdraw->withdrawn_amount, $amount, 2);
                $mWithdraw->withdrawn_amount = $withdrawn_amount;
                $before = $mWithdraw->withdrawal_amount;
                $after = bcsub($mWithdraw->withdrawal_amount, $amount, 2);
                $mWithdraw->withdrawal_amount = $after;
                $mWithdraw->save();

                $withdrawal_no = CodeExtend::uniqidDate(18, 'TX');
                $date = date('Y-m-d H:i:s');
                //账单bill日志
                $billData = [
                    'merchant_id' => $params['merchant_id'],
                    'income_amount' => $mWithdraw['income_amount'],
                    'withdrawn_amount' => $withdrawn_amount,
                    'withdrawal_amount' => $after,
                    'withdrawal_no' => $withdrawal_no,
                    'withdrawal_status' => 5,
                    'withdrawal_time' => $date,
                    'audit_time' => $date,
                    'tenant_id' => $mWithdraw->tenant_id,
                    'del_flag' => 0,
                    'gmt_created' => $date
                ];
                SysMerchantWithdrawBill::mk()->insert($billData);

                //账单log日志
                $logData = [
                    'merchant_id' => $params['merchant_id'],
                    'merchant_name' => $show['shop_name'],
                    'account_type' => 'alipay',
                    'alipay_account' => $show['alipay_account'],
                    'alipay_real_name' => $show['alipay_real_name'],
                    'withdrawal_no' => $withdrawal_no,
                    'withdrawal_amount' => $amount,
                    'withdrawal_status' => 5,
                    'withdrawal_time' => $date,
                    'withdrawal_user_id' => 20130,
                    'withdrawal_user_name' => '平台',
                    'audit_user_id' => 20130,
                    'audit_user_name' => '平台',
                    'audit_time' => $date,
                    'remark' => $params['remark'],
                    'tenant_id' => $mWithdraw->tenant_id,
                    'del_flag' => 0,
                    'gmt_created' => $date
                ];
                $logId = SysMerchantWithdrawLog::mk()->insertGetId($logData);

                //转账凭证
                $picData = [
                    'business_type' => 'WITHDRAW_PIC',
                    'relation_id' => $logId,
                    'pic' => $params['pic'],
                    'del_flag' => 0,
                    'tenant_id' => $mWithdraw->tenant_id,
                    'gmt_created' => $date
                ];
                SysPicInfo::mk()->insert($picData);
                Db::commit();
            }catch (\Exception $e){
                Db::rollback();halt($e->getMessage());
                $this->error('失败');
            }
            $this->success('操作成功');
        }


    }

    /**
     * 商家提现记录
     * @auth true
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function log()
    {
        $this->title = '商家提现列表';
        $query = SysMerchantWithdrawLog::mQuery();
        $user = $this->app->session->get('user');
        if($user['id'] != 10000) $query->where('merchant_id', '=', $user['id']);
        $query->order('withdrawal_time desc')->page();
    }

    public function _log_page_filter(array &$data){

        foreach ($data as &$vo){
            $vo['withdrawal_status_str'] = $vo['withdrawal_status'] == 5 ? '提现成功' : '待审核';
        }

    }
}